<?php

Raise::load('core.RaiseStream');
Raise::load('core.RaiseFile');

/**
 * Check whether Zlib is enabled or not
 */
if (function_exists('gzopen')) {

    /**
     * RaiseGzipFileStream class
     *
     * @link http://php.net/zlib
     * @author Sam-Mauris Yong <hellclanner at live dot com>
     * @license http://www.opensource.org/licenses/bsd-license New BSD License
     * @package Raise.Core.IO.Compression
     * @since 1.2
     */
    class RaiseGzipFileStream extends RaiseStream {

        /**
         * Create a new RaiseGzipFileStream from a RaiseFile object
         * @param RaiseFile $file
         */
        function __construct($file, $level = -1) {
            if (!($file instanceof RaiseFile)) {
                throw new RaiseInvalidArgumentException('RaiseFile was expected for $file when creating a new RaiseGzipFileStream');
            }
            $gz = gzopen($file, 'wb' . ($level >= 0 ? $level : '') . '+');
            $this->handle = gzopen($file->getPathName());
            $this->parentStream = $stream;
        }

        public function close() {
            $this->parentStream->close();
            gzclose($this->handle);
        }

        public function length() {
            $filesize = null;
            if ($this->handle) {
                $tmppos = gztell($this->handle);
                gzseek($this->handle, 0, SEEK_END);
                $filesize = gztell($this->handle);
                gzseek($this->handle, $tmppos);
            }
            return $filesize;
        }

        public function isReadable() {
            return true;
        }

        public function isSeekable() {
            return true;
        }

        public function isWriteable() {
            return true;
        }

        public function read($length) {
            return gzread($this->handle, $length);
        }

        public function readByte() {
            return ord(gzread($this->handle, 1));
        }

        public function seek($position) {
            $this->parentStream->seek($position);
            return gzseek($this->handle, $position, SEEK_SET);
        }

        public function write($str) {
            gzwrite($this->handle, $str);
        }

        public function writeByte($i) {
            gzwrite($this->handle, chr($i));
        }

    }

}